package fr.utbm.gl52.smartgrid.view;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JPanel;

import fr.utbm.gl52.smartgrid.util.Constants;
import fr.utbm.gl52.smartgrid.util.Controllable;
import fr.utbm.gl52.smartgrid.util.LibUtil;

/**
 * Panel used to select the type of Devices to add. Uses Reflection to
 * automatically find classes that match a particular parent.
 */
public class TypeSelectorPanel extends JPanel implements Controllable{

	private static final long serialVersionUID = -6704097353667486361L;

	private Class<?> parent;
	private ArrayList<JButton> buttons = new ArrayList<JButton>();

	// Layout variables
	private final int PADDING_BUTTONS = 5;

	/**
	 * 
	 * @param parent
	 *            Parent class for which we want to generate the panel, e.g.
	 *            Storage, EnergySource, ...
	 */
	public TypeSelectorPanel(Class<?> parent) {
		this(parent, null);
	}

	/**
	 * 
	 * @param parent
	 *            Parent class for which we want to generate the panel, e.g.
	 *            Storage, EnergySource, ...
	 * @param controller
	 *            The parent to be added to the buttons
	 */
	public TypeSelectorPanel(Class<?> parent, ActionListener controller) {
		super();

		this.parent = parent;

		this.setLayout(new GridLayout(1, 0, this.PADDING_BUTTONS, 0));
		this.setBackground(Color.gray);

		// Search for all classes in the model
		Class<?>[] classes = null;
		try {
			classes = LibUtil.getClasses("fr.utbm.gl52.smartgrid.model"); //$NON-NLS-1$
		} catch (Exception e) {
			e.printStackTrace();
		}

		for (int i = 0; i < classes.length; ++i) {

			// Loop on all classes found and add a button if they extend the
			// parent
			if (this.parent.isAssignableFrom(classes[i]) && !Modifier.isAbstract(classes[i].getModifiers())) {
				JButton button = new JButton(classes[i].getSimpleName());
				button.setActionCommand(Constants.PREFIX_CREATEPPTPANEL + classes[i].getName());
				button.addActionListener(controller);
				this.buttons.add(button);

				add(button);
			}
		}
	}

	/**
	 * Adds a controller to all the buttons
	 * 
	 * @param controller
	 */
	public void addController(ActionListener controller) {
		for (JButton button : this.buttons) {
			button.addActionListener(controller);
		}
	}
}